#include "const.h"

const char *v_expand(var_t v) {
	char buf[8192];

	if (!v)
		// variable is invalid, doesn't mean we should return an invalid string
		return "";

	if (v->flags & VAR_SYMLINK_BIT) {
		// symbolic link
		if (v->value.symlink==v->array.ptrvar) {
			// array pointer
			if (v->array.i!=v->array.ptrvar->array.i) {
				// the expanded token is invalid
				if (v->expanded) {
					i_delete((void *)v->expanded);
					v->expanded = (char *)0;
				}

				// note that it will be valid
				v->array.i = v->array.ptrvar->array.i;
			}
		} else {
			// normal symlink, handle
			return v_expand(v->value.symlink);
		}
	}

	if (v->flags & VAR_ARRAY_BIT)
		// yeah, just return the array itself
		return v_get(v);

	if (!v->expanded) {
		// expand the value
		v_nformat(buf, sizeof(buf), v_get(v));
		v->expanded = i_strdup(buf);
	}

	// okay, the expanded version should be valid
	return v->expanded;
}
